import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

interface ApiResponse<T = any> {
  success: boolean
  data: T
  message: string | null
}

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `logos ${token}`
      console.log('发送请求，携带token:', token.substring(0, 10) + '...')
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 简化处理
service.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    console.error('请求错误:', error)
    if (error.response) {
      // 处理 HTTP 错误状态码
      switch (error.response.status) {
        case 401:
          ElMessage.error('认证失败，请重新登录')
          router.push('/login')
          break
        case 403:
          ElMessage.error('无权访问')
          break
        case 404:
          ElMessage.error('请求资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(error.response.data?.message || '请求失败')
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    return Promise.reject(error)
  }
)

const request = async <T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> => {
  try {
    const response = await service(config)
    return response.data
  } catch (error) {
    return Promise.reject(error)
  }
}

export type { ApiResponse }
export default request